package com.sxm.yiwei.activitis;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.adapters.BillAdapter;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class BillDispathingActivity extends BaseActivity implements View.OnClickListener{

    /**
     * 发单派送中
     */
    private PullToRefreshListView dispatching;
    private SharedPreferences sharedPreferences;
    private String appId;
    private String userId;
    private String token;
    private ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    private HashMap<String, String> map;
    private final static int TYPE = 2004;
    private ImageView billdispatchingback;
    private BillAdapter billAdapter;
    private ImageView nodata;
    private ImageView backmain;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bill_dispathing);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid", "0");
        userId = sharedPreferences.getString("userId", "1");
        token = sharedPreferences.getString("token", "2");
        initDispatchingView();
        getListData();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        list.clear();
        getListData();
    }

    private void getListData() {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.SEND_BOOKLIST);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token", token);
        params.addHeader("appId", appId);
        params.addHeader("userId", userId);
        JSONObject j = new JSONObject();
        j.put("status","4");
        params.addParameter("params",j.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {



            @Override
            public void onSuccess(String result) {

               getData(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ErrType.errType(BillDispathingActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    private void getData(String result) {
        JSONObject obj = JSON.parseObject(result);
        String data = obj.getString("data");

        JSONArray array = JSONArray.parseArray(data);
        if (array.size()==0){

        }else {
            nodata.setVisibility(View.GONE);

            for (int i = 0; i < array.size(); i++) {
                map = new HashMap<>();
                JSONObject obj1 = JSON.parseObject(String.valueOf(array.get(i)));
                String consignorAddr = obj1.getString("consignorAddr");
                String id = obj1.getString("id");
                String intro = obj1.getString("intro");
                String introImage = obj1.getString("introImage");
                String orderCode = obj1.getString("orderCode");
                String totalAmount = obj1.getString("totalAmount");
                String publishTime = obj1.getString("publishTime");
                String  courierMobile = obj1.getString("courierMobile");
                String  courierNickname = obj1.getString("courierNickname");
                String type = obj1.getString("type");
                map.put("consignorAddr",consignorAddr);
                map.put("courierMobile",courierMobile);
                map.put("id",id);
                map.put("intro",intro);
                map.put("introImage",introImage);
                map.put("orderCode",orderCode);
                map.put("totalAmount",totalAmount);
                map.put("publishTime",publishTime);
                map.put("type",type);
                list.add(map);

            }
        }

        billAdapter = new BillAdapter(BillDispathingActivity.this, list,TYPE);
        dispatching.setAdapter(billAdapter);
        billAdapter.setOnClick(new BillAdapter.Callback() {
            @Override
            public void onclick(int v) {
                HashMap<String,String> map1 = (HashMap<String, String>) billAdapter.getItem(v);
                String id1 = map1.get("id");
                final String courierMobile = map1.get("courierMobile");
                final AlertDialog.Builder builder1 = new AlertDialog.Builder(BillDispathingActivity.this,R.style.NoBackGroundDialog);
                View view1 = LayoutInflater.from(BillDispathingActivity.this).inflate(R.layout.cancel_servicedialog, null);
                Button cancelbt1 = (Button) view1.findViewById(R.id.cancel_cancelbt);
                Button surebt1 = (Button) view1.findViewById(R.id.cancel_surebt);
                TextView t11 = (TextView) view1.findViewById(R.id.cancel_t1);
                final TextView t21 = (TextView) view1.findViewById(R.id.cancel_t2);
                builder1.setView(view1);
                t11.setText("");
                t21.setText(courierMobile);
                surebt1.setText("呼叫");
                final AlertDialog alertDialog = builder1.create();
                cancelbt1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        alertDialog.dismiss();
                    }
                });
                surebt1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        String callno = (String) t21.getText();
                        Intent callintent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+courierMobile));
                        if (ActivityCompat.checkSelfPermission(BillDispathingActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                            // TODO: Consider calling
                            //    ActivityCompat#requestPermissions
                            // here to request the missing permissions, and then overriding
                            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                            //                                          int[] grantResults)
                            // to handle the case where the user grants the permission. See the documentation
                            // for ActivityCompat#requestPermissions for more details.
                            return;
                        }
                        startActivity(callintent);
                        alertDialog.dismiss();
                    }
                });
                alertDialog.show();
            }

            @Override
            public void onclick1(int v) {
                HashMap<String,String> map1 = (HashMap<String, String>) billAdapter.getItem(v);
                String id1 = map1.get("id");
                String type = map1.get("type");
                Intent i = null;
                if (type.equals("1")){
                    i = new Intent(BillDispathingActivity.this,BookContentOnceActivity.class);
                }else if (type.equals("2")){
                    i = new Intent(BillDispathingActivity.this,BookContentHotActivity.class);
                }else {
                    i = new Intent(BillDispathingActivity.this,BookContentHelpActivity.class);
                }
                i.putExtra("id",id1);
                i.putExtra("TYPE",TYPE);
                i.putExtra("type",type);

                // 进入详情页 传入订单id
                startActivity(i);
            }
        });
        dispatching.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                list.clear();
                getListData();
                new FinishRefresh().execute();
            }
        });
        billAdapter.notifyDataSetChanged();

    }

    private void initDispatchingView() {
        dispatching = (PullToRefreshListView) findViewById(R.id.disaptchinglist);
        billdispatchingback = (ImageView) findViewById(R.id.billdispatching_back);
        nodata = (ImageView) findViewById(R.id.billdis_nodata);
        backmain = (ImageView) findViewById(R.id.billdis_backmain);
        backmain.setOnClickListener(this);
        billdispatchingback.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.billdispatching_back:
                finish();
                break;
            case R.id.billdis_backmain:
                startActivity(new Intent(BillDispathingActivity.this, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;

        }
    }

    private class FinishRefresh extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {

            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            billAdapter.notifyDataSetChanged();
            dispatching.onRefreshComplete();
        }
    }
}
